package com.yucc.girlimages.ui;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Window;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.umeng.analytics.MobclickAgent;
import com.umeng.api.sns.UMSNSException;
import com.umeng.api.sns.UMSnsService;
import com.umeng.api.sns.UMSnsService.DataSendCallbackListener;
import com.umeng.api.sns.UMSnsService.RETURN_STATUS;
import com.umeng.fb.NotificationType;
import com.umeng.fb.UMFeedbackService;
import com.yucc.girlimages.Config;
import com.yucc.girlimages.GirlsApplication;
import com.yucc.girlimages.R;
import com.yucc.girlimages.util.cache.Utils;

/**
 * 
 * @author yucc
 * @category 所有Activity类的基类，添加额外的功能设置
 * 
 */
public abstract class BaseActivity extends SherlockFragmentActivity {
	public static final String EXIT_ACTION = "com.fanhuan.app.exitapp";
	
	public static final String EXTRA_IMAGE_DIR = "extra_image_dir";

	// 区分行为的掩码
	protected static final int RECEIVER_MASK = 0x00000001;
	protected static final int BACKGROUND_MASK = 0x00000010;

	// 行为代码
	protected static final int ACTION_NOTHING = 0x00000000;
	protected static final int ACTION_REGISTE_RECEIVE = 0x00000001;
	protected static final int ACTION_SET_BACKGROUND = 0x00000010;
	protected static final int ACTION_SET_BACKGROUND_AND_RECEIVER = 0x00000011;

	protected static final int REQUEST_CODE_NETWORK_SETTING = 1 ;

	// _onCreate 返回的行为码
	private int actionCode;
	
	protected boolean isUnlocked ;

	// 用来接收退出应用请求的广播
	private ExistBroadCastReceiver receiver;
	
	private byte [] mBytesForShare ;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		if(!Utils.hasActionBar()) requestWindowFeature(Window.FEATURE_NO_TITLE) ;
		
		actionCode = _onCreate(savedInstanceState);
		
		if (shouldRegistReceiver(actionCode)) {
			// 实例化并注册接收器
			receiver = new ExistBroadCastReceiver();
			this.registerReceiver(receiver, new IntentFilter(EXIT_ACTION));
		}

		if (shouldSetBackground(actionCode)) {
			// 统一设置背景图片
			getWindow().setBackgroundDrawableResource(R.color.background_color);
		}
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPause(this) ;
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onResume(this) ;
		isUnlocked = getSharedPreferences(Config.SHAF_NAME, MODE_PRIVATE).getBoolean(Config.SHAF_UNLOCKED, false) ;
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //Used to put dark icons on light action bar

        menu.add("分享").setIcon(android.R.drawable.ic_menu_share)
            .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        if(!Utils.hasActionBar())
        menu.add("反馈").setIcon(android.R.drawable.ic_menu_edit)
        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

        return true;
    }
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if("分享".equals(item.getTitle())){
			prepreForShare() ;
			shareImage() ;
			return true ;
		} else if("反馈".equals(item.getTitle())){
			UMFeedbackService.enableNewReplyNotification(
					this, NotificationType.AlertDialog);
			UMFeedbackService.setGoBackButtonVisible();

			UMFeedbackService.openUmengFeedbackSDK(this);
		}
		return super.onOptionsItemSelected(item);
	}
	
	// SNS分享图片，使用异步初始化加载
	private void shareImage() {
		MobclickAgent.onEvent(this, "share") ;
		DataSendCallbackListener listener = new DataSendCallbackListener() {
			@Override
			public void onDataSendFailedWithException(UMSNSException exception,
					UMSnsService.SHARE_TO userPlatform) {
				exception.printStackTrace();
			}

			@Override
			public void onDataSendFinished(RETURN_STATUS returnStatus,
					UMSnsService.SHARE_TO userPlatform) {
				switch (returnStatus) {
				case UPDATED:
//					HashMap<String, String> map = new HashMap<String, String>() ;
//					map.put("platform", userPlatform.name()) ;
					MobclickAgent.onEvent(BaseActivity.this,"share_success",userPlatform.name());
					((GirlsApplication) getApplication()).showToast("感谢您的分享.");
					break;
				case REPEATED:
					((GirlsApplication) getApplication()).showToast("重复的内容分享.");
					break;
				default:
					break;
				}
			}
		};
		UMSnsService.share(this, mBytesForShare, new HashMap<String, String>(),
				listener);
	}
	
	//提前做好分享的数据准备
  	protected void prepreForShare() {
		Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.blackyarm);
  		
  		ByteArrayOutputStream stream = new ByteArrayOutputStream();
  		BufferedOutputStream bos = new BufferedOutputStream(stream,
  				Utils.IO_BUFFER_SIZE);
  		bmp.compress(Bitmap.CompressFormat.JPEG, 90, bos);
  		mBytesForShare = stream.toByteArray();
  	}
	
	/**
	 * 子类返回一个行为代码，用于区分子类需要的行为
	 * 
	 * @param savedInstanceState
	 * @return
	 */
	protected abstract int _onCreate(Bundle savedInstanceState);

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (shouldRegistReceiver(actionCode))
			unregisterReceiver(receiver);
	}

	/**
	 * @param code
	 * @return true，则注册，false，为不注册 判断是否需要注册广播接收器
	 */
	private static final boolean shouldRegistReceiver(int code) {
		if ((code & RECEIVER_MASK) != 0)
			return true;
		else
			return false;
	}

	/**
	 * @param code
	 * @return true，则设置背景图，false，为不设置 判断是否需要设置背景图片
	 */
	private static final boolean shouldSetBackground(int code) {
		if ((code & BACKGROUND_MASK) != 0)
			return true;
		else
			return false;
	}
	
	protected final Toast getToast(String text){
		Toast toast = getGirlsApplication().getToast() ;
		toast.setDuration(0) ;
		toast.setText(text);
		return toast ;
	}
	protected final Toast getToast(int resId){
		return getToast(getResources().getString(resId) ) ;
	}
	protected final Toast getToast(){
		return getToast("no message") ;
	}
	
	protected GirlsApplication getGirlsApplication() {
		return ((GirlsApplication)getApplication()) ;
	}

	/**
	 * 自定义的广播接收类
	 */
	class ExistBroadCastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			finish();
		}
	}
}
